<?php


namespace app\portal\controller;

use app\portal\model\ContestCategoryPostModel;
use app\portal\model\ContestModel;
use app\portal\model\ScoreModel;
use app\portal\model\UserModel;
use app\portal\model\WorksModel;
use cmf\controller\HomeBaseController;
use think\Model;

class WorksController extends HomeBaseController
{

    public function index() {
        $workModel = new WorksModel();
        $workId  = $this->request->param('id', 0, 'intval');
        $work = $workModel->alias('w')
            ->join('user u', 'w.user_id = u.id')
            ->where('w.id',$workId)
            ->field('w.*,u.user_nickname')
            ->find();
        if(!empty($work)) {
            $work['more_s'] = json_decode($work['more'],true);
            $work['more'] = $work['more_s'];
        }
        $scores = $work->comm()->select()->toArray();
        foreach ($scores as $s => $c) {
            $review = UserModel::find($c['review_id']);
            $scores[$s]['review_name'] = $review['user_nickname'];
        }

        $this->assign('work',$work);
        $this->assign('scores',$scores);
        return $this->fetch('/work');
    }

    /**
     * 提交作品页面
     * @return mixed|string|\think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add() {
        $user = cmf_get_current_user();
        if(!$user) {
            return redirect('/user/login');
        }
        $update_str = 0;
        $contestModel = new ContestModel();
        $contest = $contestModel->where('status',1)->find();
        if(!empty($contest)) {
            #查询赛事全部分类
            $contestCategoryPostModel = new ContestCategoryPostModel();
            $categories = $contestCategoryPostModel->getCate($contest['id']);
            #查询上传作品
            $workModel = new WorksModel();
            $work = $workModel->where('contest_id',$contest['id'])->where('user_id',$user['id'])->find();
            if(!empty($work)) {
                $work['more_s'] = json_decode($work['more'],true);
                $work['more'] = $work['more_s'];
            }
            #判断是否在报名时间
            $end = (int)$contest['apple_end'];
            if($end < time()) {
                $update_str = 1;
            }
            $this->assign('categories',$categories);
            $this->assign('work',$work);
        }

        $this->assign('update_str',$update_str);
        $this->assign('contest',$contest);
        $this->assign($user);
        return $this->fetch('../user/profile/upload_work');
    }

    /**
     * 上传作品
     */
    public function addPost() {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $worksModel = new WorksModel();

            if(isset($data['post']['user_id'])) {
                $user = UserModel::find($data['post']['user_id']);
                if($user['user_type'] != 4) {
                    $this->error('您不是参赛人员，禁止上传作品');
                }
            }
            if($data['post']['contest_category'] == 0) {
                $this->error('请选择赛事类别');
            }
            if(empty($data['post']['title'])) {
                $this->error('请输入作品标题');
            }
            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }
            if(empty($data['post']['id'])) {
                unset($data['post']['id']);
                $worksModel->adminAddWork($data['post']);
            }
            else {
                $worksModel->adminEditWork($data['post']);
            }


            $data['post']['id'] = $worksModel->id;
            $hookParam          = [
                'is_add'  => true,
                'works' => $data['post']
            ];
            hook('portal_admin_after_save_works', $hookParam);


//            $this->success('添加成功!', url('AdminArticle/edit', ['id' => $worksModel->id]));
            $this->success('添加成功!');
        }
    }

    /**
     * 作品评分页面
     * @return mixed|string|\think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function review() {
        $user = cmf_get_current_user();
        $review_str = 0;
        if(!$user) {
            return redirect('/user/login');
        }
        $param = $this->request->param();

        $contestModel = new ContestModel();
        $contest = $contestModel->where('status',1)->find();
        if(!empty($contest)) {
            #查询赛事全部分类
            $contestCategoryPostModel = new ContestCategoryPostModel();
            $categories = $contestCategoryPostModel->getCate($contest['id']);

            #查询当前赛事下的全部作品
            $workModel = new WorksModel();
            $param['contest_id'] = $contest['id'];
            $param['contest_category'] = isset($param['contest_category'])?(int)$param['contest_category']:0;
            $param['review_id'] = $user['id'];
            $works = $workModel->getWorkList($param);
//        dump($works);
//        die();
//        foreach ($works as $w => $k) {
//            $scores = $k->comm()->select()->toArray();
//            foreach ($scores as $s => $c) {
//                $review = UserModel::find($c['review_id']);
//                $scores[$s]['review_name'] = $review['user_nickname'];
//            }
//            $works[$w]['scores'] = $scores;
//        }
            if($contest['review_start'] < time() && $contest['review_end'] > time()) {
                $review_str = 1;
            }
            $this->assign('works',$works);
            $this->assign('review_str',$review_str);
            $this->assign('categories',$categories);
            $this->assign('page', $works->render());
        }
        $this->assign($user);
        $this->assign('contest',$contest);

        $this->assign('param', $param);

        return $this->fetch('../user/profile/review_work');
    }

    /**
     * 评委我的打分页面
     * @return mixed|string|\think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function my_review() {
        $user = cmf_get_current_user();
        if(!$user) {
            return redirect('/user/login');
        }
        # 获取该评委打分的全部作品
        $workModel = new WorksModel();
        $scoreModel = new ScoreModel();
//        $works = $workModel->getReviewList($user['id']);
        $works = $scoreModel->getReviewList($user['id']);
        foreach ($works->getCollection() as $key => $val) {
            if($val['review_start'] < time() && $val['review_end'] > time()) {
                $works->getCollection()[$key]['review_str'] = 1;
            }
            else {
                $works->getCollection()[$key]['review_str'] = 0;
            }
        }
//        echo json_encode($works);
//        die();

        $contestModel = new ContestModel();
        $contest = $contestModel->where('status',1)->find();

        $this->assign($user);
        $this->assign('works',$works);
        $this->assign('contest',$contest);
        $this->assign('page', $works->render());
        return $this->fetch('../user/profile/my_review');
    }

    /**
     * 打分弹窗页面
     * @return mixed
     */
    public function reviewWindow() {
        $id = $this->request->param('id');
        $user = cmf_get_current_user();
        if(!$user) {
            return redirect('/user/login');
        }
        $workModel = new WorksModel();
        $work = $workModel->find($id);
        $contestModel = new ContestModel();
        $contest = $contestModel->find($work['contest_id']);
        $scoreModel = new ScoreModel();
        $score = $scoreModel->where('work_id',$work['id'])->where('review_id',$user['id'])->find();
        $this->assign('work',$work);
        $this->assign('contest',$contest);
        $this->assign('score',$score);
        $this->assign('user',$user);
        return $this->fetch('../user/profile/review_window');
    }

    /**
     * 提交打分
     */
    public function reviewPost() {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $user = cmf_get_current_user();
            if($user['user_type'] != 3) {
                $this->error("您不是评委，请联系管理员！");
            }

            $scoreModel = new ScoreModel();
            $some = $scoreModel->where('work_id',$data['work_id'])->where('review_id',$data['review_id'])->find();
            if(empty($some)) {
                $score = $scoreModel->save($data);
            }else {
                $score = $scoreModel
                    ->where('work_id',$data['work_id'])
                    ->where('review_id',$data['review_id'])
                    ->where('contest_id',$data['contest_id'])
                    ->update(['score'=>$data['score']]);
            }
            if($score) {
                $this->success("打分成功！");
            }
            else {
                $this->error("打分失败！");
            }
        }
    }
}